package kxfang.com.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroupOverlay;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import com.blankj.utilcode.util.ToastUtils;
import com.hjq.umeng.Platform;
import com.hjq.umeng.UmengShare;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import kxfang.com.common.R;
import kxfang.com.common.dialog.MessageDialog;
import kxfang.com.common.dialog.ShareDialog;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.views.BaseDialog;

/**
 * Created by ZJ
 * on 2019/11/19
 * Class Content 帮助类
 */
public class MyUtils {
    public static String data;
    public static String sdCardDir = Environment.getExternalStorageDirectory() + "/images/";

    private static long lastClickTime;

    private static WaitDialog.Builder waitDialog;

    /**
     * 去除小数点后为0的显示
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

    public static void setBackgroundAlpha(Context mContext, float bgAlpha) {

        if (bgAlpha == 1f) {
            clearDim((Activity) mContext);
        } else {
            applyDim((Activity) mContext, bgAlpha);
        }
    }

    private static void clearDim(Activity activity) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView();
            //activity跟布局
//        ViewGroup parent = (ViewGroup) parent1.getChildAt(0);
            ViewGroupOverlay overlay = parent.getOverlay();
            overlay.clear();
        }
    }

    private static void applyDim(Activity activity, float bgAlpha) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView();
            //activity跟布局
//        ViewGroup parent = (ViewGroup) parent1.getChildAt(0);
            Drawable dim = new ColorDrawable(Color.BLACK);
            dim.setBounds(0, 0, parent.getWidth(), parent.getHeight());
            dim.setAlpha((int) (255 * bgAlpha));
            ViewGroupOverlay overlay = parent.getOverlay();
            overlay.add(dim);
        }
    }

    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取图片并压缩
     *
     * @param imagePath
     * @return
     */
    public static String ysbitmao(String imagePath) {
        return compressImage(imagePath);
    }

    /**
     * 图片压缩
     *
     * @param bitmap bitmap
     * @return base64
     */
    public static String compressImage(Bitmap bitmap) {
        if (bitmap == null) {
            return "";
        }
        String decodeStr = compressImageBit(bitmap);
        try {
            if (bitmap != null) {
                bitmap.recycle();
            }
        } catch (Exception e) {
        }
        return decodeStr;
    }

    /**
     * 图片压缩
     * @param path 路径
     * @return base64
     */
    public static String compressImage(String path){
        return compressImage(BitmapFactory.decodeFile(path));
    }

    // 将字符串转换成Bitmap类型
    public static String stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return saveBitmap(bitmap);
    }


    public static String saveBitmap(Bitmap bitmap) {
        try {
            File dirFile = new File(sdCardDir);
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            File file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            bitmap.recycle();
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static String compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 800f;
        float ww = 480f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImageBit(bitmap);// 压缩好比例大小后再进行质量压缩
        //return bitmap;
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    private static String compressImageBit(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 1024) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5;// 每次都减少10
        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
//        return bitmap;
        byte[] bytes = baos.toByteArray();
        //base64 encode
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);
        try {
            baos.close();
            image.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encodeString;
    }
    /**
     * 返回当前程序版本号
     */
    public static String getAppVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception" + e);
        }
        return "1.0.0";
    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     */
    public static void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    //////////////////////////////////////////////截图//////////////////////////////////////////
    public static Bitmap loadBitmapFromView(WebView activity, String filePath) {
        Picture picture = activity.capturePicture();
        Bitmap bitmap = null;
        int width = picture.getWidth();
        int height = picture.getHeight();
        if (width > 0 && height > 0) {
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            picture.draw(canvas);
        }
        //获取图片
        File file = new File(filePath);
        if (!file.exists())
            file.mkdirs();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file.getPath() + "/" + "share.jpg");
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 创建文件夹
     *
     * @param filePath
     * @return
     */
    public static String createImagePath(String filePath) {
        //判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件全名
            File file = new File("/storage/emulated/0" + filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            return file.toString();
        }
        return "";
    }


    /**
     * 获取屏幕高度
     *
     * @param activity
     * @return
     */
    public static int getSceenHeight(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getHeight();
    }

    /**
     * 获取屏幕宽度
     *
     * @param activity
     * @return
     */
    public static int getSceenWidth(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getWidth();
    }

    public static void downApk() {

    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {

        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight();//统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public static String getTime(String curtimeStr, String endtimeStr) {
        String str = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timeMillis = System.currentTimeMillis();
        if (curtimeStr.isEmpty()) {
            curtimeStr = stampToDate(timeMillis);
        }
        if (endtimeStr.isEmpty()) {
            endtimeStr = stampToDate(timeMillis);
        }
        Date curDate = null;
        Date endDate = null;
        try {
            curDate = df.parse(curtimeStr);
            endDate = df.parse(endtimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = endDate.getTime() - curDate.getTime();
//        Log.i("tag", "时间差=" + diff);
        //以天数为单位取整
        Long day = diff / (1000 * 60 * 60 * 24);
        //以小时为单位取整
        Long hour = (diff / (60 * 60 * 1000) - day * 24);
        //以分钟为单位取整
        Long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        //以秒为单位
        Long second = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        if (day > 0) {
            str = String.valueOf(day).concat("天前");
        } else if (hour > 0) {
            str = String.valueOf(hour).concat("小时前");
        } else if (min > 0) {
            str = String.valueOf(min).concat("分钟前");
        } else if (second > 0) {
            str = String.valueOf(second).concat("秒前");
        } else {
            str = "刚刚";
        }
        return str;
    }

    /**
     * 将时间戳转换为时间
     */

    public static String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);

    }

    /**
     * 转换html格式
     *
     * @param str
     * @return
     */
    public static String toHtml(String str) {
        if (str == null) {
            return "";
        } else {
//            str = str.replaceAll("<", "&lt;");
//            str = str.replaceAll(">", "&gt;");
//            str = str.replaceAll("'", "''");
//            str = str.replaceAll(" ", "&nbsp;");
            str = str.replaceAll("\n", "<br/>");
        }
        return str;
    }
    //

    /**
     * dp转px
     *
     * @param context
     * @param dpVal
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * 将包含.的字符串转换为int
     *
     * @return
     */
    public static int stringToInt(String s) {
        if (!s.contains(".")) {
            return 0;
        }
        String replace = s.replace(".", "");
        try {
            return Integer.parseInt(replace);
        } catch (Exception e) {

        }
        return 0;
    }

    //手机号正则
    public static boolean isPhone(String str) throws PatternSyntaxException {
        String regExp = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    //统一拨打电话方式
    public static void callPhone(Context context, String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNumber);
        intent.setData(data);
        context.startActivity(intent);
    }


    /**
     * 分享dialog
     * @param context
     */
    public static void shareDialog(Context context,String url,String title,String content,String img) {
        // 分享对话框
        new ShareDialog.Builder(context)
                // 分享链接
                .setShareUrl(url)
                // 分享标题
                .setShareTitle(title)
                // 分享描述
                .setShareDescription(content)
                // 分享缩略图
                .setShareLogo(img)

                .setListener(new UmengShare.OnShareListener() {

                    @Override
                    public void onSucceed(Platform platform) {
                        ToastUtils.showShort("分享成功");
                    }

                    @Override
                    public void onError(Platform platform, Throwable t) {
                        ToastUtils.showShort(t.getMessage());
                    }

                    @Override
                    public void onCancel(Platform platform) {
                        ToastUtils.showShort("分享取消");
                    }
                })
                .show();
    }

    /**
     * 统一登录弹窗
     *
     * @param context
     */
    public static void myShowDialog(Context context) {
        new MessageDialog.Builder(context)
                .setMessage("您还未登录，请先登录")
                .setConfirm("去登录")
                .setCancel("取消")
                .setAutoDismiss(true)
                .setListener(dialog -> RouterUtils.navigate(RoutHub.PAGER_LOGIN))
                .show();
    }



    /**
     * 等待加载弹窗
     *
     * @param context
     */
    public static void showLoading(Context context) {
        loadingDialog(context,"加载中···");
    }

    public static void loadingDialog(Context context,String s) {
        waitDialog= new WaitDialog.Builder(context);
        waitDialog.setMessage(s).show();
    }

    public static void disLoading(){
        if (waitDialog != null){
            if (waitDialog.isShowing()){
                waitDialog.dismiss();
            }
        }
    }

    /**
     * 动态设置lable标签
     *
     * @param context
     * @param type
     * @param list
     * @param labelLayout
     */
    public static void setLabel(Context context, int type, List<String> list, LinearLayout labelLayout) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < list.size(); i++) {
            TextView textView = new TextView(context);
            textView.setText(list.get(i));
//            if (type == 1) {
            textView.setTextColor(context.getResources().getColor(R.color.common_color_2947));
            textView.setBackgroundResource(R.drawable.shape_manjian_red_bg);
//            } else {
//                textView.setText();
//            }
            textView.setPadding(10, 5, 10, 5);
            textView.setTextSize(9);
            lp.setMargins(0, 0, ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, context.getResources().getDisplayMetrics())), 0);
            textView.setLayoutParams(lp);
            labelLayout.addView(textView);
        }
    }



    public static boolean isFastClick(int millisecond) {
        long curClickTime = System.currentTimeMillis();
        long interval = (curClickTime - lastClickTime);

        if (0 < interval && interval < millisecond) {
            // 超过点击间隔后再将lastClickTime重置为当前点击时间
            return true;
        }
        lastClickTime = curClickTime;
        return false;
    }


    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

}
